﻿using HotelManager.Common;
using HotelManager.Extensions;
using HotelManager.Models.Params;
using HotelManager.Service;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Shapes;

namespace HotelManager.ViewModels
{
    public class LoginViewModel:BindableBase,IDialogAware
    {
        private readonly string filterName = "Login";
        private readonly IEventAggregator aggregator;
        private readonly ILoginService loginService;
        public LoginViewModel(ILoginService _loginService, IEventAggregator aggregator)
        {
            ExecuteCommand = new DelegateCommand<string>(Execute);
            loginService = _loginService;
            this.aggregator = aggregator;
        }
        private void Execute(string obj)
        {
            switch (obj)
            {
                case "login": Login(); break;
                case "cancel": Reset(); break;
            }
        }
        private async void Login()
        {
            if (string.IsNullOrWhiteSpace(Account) || string.IsNullOrWhiteSpace(PassWord))
                return;
            var loginResult = await loginService.LoginAsync(new LoginParam()
            {
                loginId = Account,
                loginPwd = PassWord
            });
            if (loginResult.success)
            {
                AppSession.UserName = loginResult.data.name;
                AppSession.LoginId = loginResult.data.loginId;
                AppSession.RoleId = loginResult.data.roleId;
                AppSession.Phone = loginResult.data.phone;
                AppSession.Photo = loginResult.data.photo;
                RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
                return;
            }
            aggregator.SendMessage(loginResult.message, filterName);
        }
        private void Reset()
        {
            Account = "";
            PassWord = "";
        }

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            RequestClose?.Invoke(new DialogResult(ButtonResult.No));
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            
        }

        private string account;

        public string Account
        {
            get { return account; }
            set { account = value; RaisePropertyChanged(); }
        }
        private string passWord;

        public event Action<IDialogResult> RequestClose;

        public string PassWord
        {
            get { return passWord; }
            set { passWord = value; RaisePropertyChanged(); }
        }
        public DelegateCommand<string> ExecuteCommand { get; private set; }

        public string Title => "登录";
    }
}
